package com.mhy.emoji;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.util.Log;
import android.widget.TextView;

import com.mhy.pickerview.R;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EmojiUtil {

    /**
     * 将code 值 例如1F601 转化为字符串直接赋值给TextView
     *
     * @param emojiCode
     * @return
     */
    public static String codeToString(String emojiCode) {
        String str = "";
        try {
            str = new String(Character.toChars(Integer.parseInt(emojiCode, 16)));
        } catch (Exception e) {
            str = emojiCode;
        }
        return str;
    }

    /**
     * 将字符串中 表情标签 例如[笑脸] 转化为 图片☺
     *
     * @param context
     * @param builder
     * @param nameLength
     * @param mHashMap
     * @return
     */
    public static SpannableStringBuilder strToEmotion(Context context, SpannableStringBuilder builder, int nameLength, HashMap<String, Integer> mHashMap) {
        //评论的用户名 不需要检查是否有emotion表情，只检查评论内容
        int start = nameLength;
        int end = nameLength;
        int resId = -1;//图片资源id


        try {
            String content = builder.subSequence(nameLength, builder.length()).toString();
            if (content.contains("[") && content.contains("]")) {
                start += content.indexOf("[");
                end += content.indexOf("]");
                if (end > start) {
                    String label = builder.subSequence(start, end + 1).toString();
                    resId = mHashMap.get(label);

                    if (resId != -1) {
                        //笑脸图片 取代 标签[笑脸]
                        ImageSpan imageSpan = new ImageSpan(context, resId);
                        builder.setSpan(imageSpan, start, end + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        strToEmotion(context, builder, end + 1, mHashMap);
                    } else {
                        //没有可以匹配的 标签
                        return builder;
                    }

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return builder;
    }

    /**
     * 对spanableString进行正则判断，如果符合要求，则以表情图片代替
     *
     * @param context
     * @param spannableString
     * @param patten
     * @param start
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws NumberFormatException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void dealExpression(Context context, SpannableString spannableString, Pattern patten, int start) throws SecurityException, NoSuchFieldException, NumberFormatException, IllegalArgumentException, IllegalAccessException {
        Matcher matcher = patten.matcher(spannableString);
        while (matcher.find()) {
            String key = matcher.group();
            if (matcher.start() < start) {
                continue;
            }
            Field field = R.drawable.class.getDeclaredField(key);
            int resId = Integer.parseInt(field.get(null).toString());       //通过上面匹配得到的字符串来生成图片资源id
            if (resId != 0) {
                Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), resId);
                bitmap = Bitmap.createScaledBitmap(bitmap, 60, 60, false);//设置表情大小
                ImageSpan imageSpan = new ImageSpan(bitmap);                //通过图片资源id来得到bitmap，用一个ImageSpan来包装
                int end = matcher.start() + key.length();                   //计算该图片名字的长度，也就是要替换的字符串的长度
                spannableString.setSpan(imageSpan, matcher.start(), end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);   //将该图片替换字符串中规定的位置中
                if (end < spannableString.length()) {                       //如果整个字符串还未验证完，则继续。。
                    dealExpression(context, spannableString, patten, end);
                }
                break;
            }
        }
    }

    /**
     * 得到一个SpanableString对象，通过传入的字符串,并进行正则判断
     *
     * @param context
     * @param str
     * @return
     */
    public static SpannableString getExpressionString(Context context, String str, String zhengze) {
        SpannableString spannableString = new SpannableString(str);
        Pattern sinaPatten = Pattern.compile(zhengze, Pattern.CASE_INSENSITIVE);        //通过传入的正则表达式来生成一个pattern
        try {
            dealExpression(context, spannableString, sinaPatten, 0);
        } catch (Exception e) {
            Log.e("dealExpression", e.getMessage());
        }
        return spannableString;
    }

    public static SpannableString getEmotionContent(final Context context, final TextView tv, String source) {
        SpannableString spannableString = new SpannableString(source);
        Resources res = context.getResources();

        String regexEmotion = "\\[([\u4e00-\u9fa5\\w])+\\]";
        Pattern patternEmotion = Pattern.compile(regexEmotion);
        Matcher matcherEmotion = patternEmotion.matcher(spannableString);

        while (matcherEmotion.find()) {
            // 获取匹配到的具体字符
            String key = matcherEmotion.group();
            // 匹配字符串的开始位置
            int start = matcherEmotion.start();
            // 利用表情名字获取到对应的图片
            Integer imgRes = getImgByName(key);
            if (imgRes != null) {
                // 压缩表情图片
                int size = (int) tv.getTextSize();
                Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
                Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);

                ImageSpan span = new ImageSpan(context, scaleBitmap);
                spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return spannableString;
    }

   private static Map<String, Integer> map = new HashMap<>();//资源id映射
    private static Integer getImgByName(String key) {
        return map.get(key);
    }

   private static Map<String, String> emojiMap = new HashMap<>();

    public static void weiboEmoji() {
        StringBuilder sb = new StringBuilder();

        String names = "[羞羞哒甜馨][萌神奥莉][带着微博去旅行][爱红包][拍照][马到成功]→_→[呵呵][嘻嘻][哈哈][爱你][挖鼻屎][吃惊][晕][泪][馋嘴][抓狂][哼][可爱][怒][汗][害羞][睡觉][钱][偷笑][笑cry][doge][喵喵][酷][衰][闭嘴][鄙视][花心][鼓掌][悲伤][思考][生病][亲亲][怒骂][太开心]" +
                "[懒得理你][右哼哼][左哼哼][嘘][委屈][吐][可怜][打哈气][挤眼][失望][顶][疑问][困][感冒][拜拜][黑线][阴险][打脸][傻眼][互粉][心][伤心][猪头][熊猫][兔子]";

        String regexEmoji = "\\[([\u4e00-\u9fa5a-zA-Z0-9])+\\]";
        Pattern patternEmoji = Pattern.compile(regexEmoji);
        Matcher matcherEmoji = patternEmoji.matcher(names);


        while (matcherEmoji.find()) { // 如果可以匹配到
            String key = matcherEmoji.group(); // 获取匹配到的具体字符

            String pinyinName = "d_" + emojiMap.get(key).replace("[", "").replace("]", "");
            sb.append("emojiMap.put(\"" + key + "\", R.drawable." + pinyinName + ");\n");
        }
        System.out.println(sb.toString());
    }


}
